package logic

import (
	"context"
	"errors"
	"shuqi-novel/mysql"
	"shuqi-novel/pkg"
	"strconv"

	"shuqi-novel/userrpc/internal/svc"
	"shuqi-novel/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户登录
func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	err := user.Login(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err
	}

	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}

	if user.Password != in.Password {
		return nil, errors.New("密码错误")
	}

	handler, err := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	if err != nil {
		return nil, err
	}

	return &userrpc.LoginResponse{
		Token: handler,
	}, nil
}
